package com.apobates.jforum2.troll.nest.websocket;

import com.apobates.jforum2.troll.nest.service.LetterClient;
import com.apobates.jforum2.troll.notices.stub.vo.LetterDigestVo;
import com.apobates.jforum2.troll.utils.core.Commons;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
 * 消息推送
 *
 * @author xiaofanku
 * @since 20200527
 */
public class MessageSocketPushHandler extends TextWebSocketHandler {
    @Autowired
    private LetterClient letterClient;
    private final static Logger logger = LoggerFactory.getLogger(MessageSocketPushHandler.class);

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        //{"id":"memberId", "ux":"previousUx","cmd":"unread_size"} //1未读的消息数量
        //{"id":"memberId", "sender":"消息的发送方", "ux":"previousUx","cmd":"body_list"} //2消息内容页
        String cmdMsg = message.getPayload();
        logger.info("[MessagePushHandler]sock.js cmd: " + cmdMsg);
        String responseData = null;
        Map<String, Long> jsonData = Commons.fromStatsString(cmdMsg);
        long cmdSybol = 0;
        try {
            cmdSybol = jsonData.get("cmd");
        } catch (NullPointerException e) {
        }

        if (cmdSybol == 1) {
            responseData = updateUnReadMessages(jsonData.get("id"), jsonData.get("ux").intValue());
        }
        if (cmdSybol == 2) {
            responseData = updateMessageBody(jsonData.get("id"), jsonData.get("sender"), jsonData.get("ux").intValue());
        }
        //
        if (null == responseData) {
            return;
        }
        //
        String id = session.getId();
        try {
            session.sendMessage(new TextMessage(responseData));
        } catch (IOException e) {
            logger.info("[MessagePushHandler]session id: " + id + ", exception: " + e.getMessage());
        }
    }
    //未读消息的数量
    private String updateUnReadMessages(long memberId, int previousUx) {
        Long size = letterClient.getUnReadSize(memberId);
        return new Gson().toJson(Map.ofEntries(Map.entry("id", memberId), Map.entry("result", size)));
    }
    //发件人/收件人最近的消息内容
    private String updateMessageBody(long receiver, long sender, int previousUx) {
        //old:
        //ForumLetter--->MessageBodyDigest
        //List<MessageBodyDigest> data = inboxService.get(sender, receiver, previousUx).map(fm -> new MessageBodyDigest(fm, receiver)).collect(Collectors.toList());
        //new:
        List<LetterDigestVo> data = letterClient.getByPrevious(sender, receiver, previousUx);
        return new Gson().toJson(data);
    }
}
